package com.itic.appbase.applications.files.upload;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.itic.appbase.applications.files.persistence.model.Files;
import com.itic.appbase.applications.files.service.FilesService;
import com.itic.appbase.applications.files.upload.service.FileUploadService;
import com.itic.appbase.applications.files.utils.FileHelper;
import com.itic.appbase.applications.files.utils.FileValidatorHelper;
import com.itic.appbase.framework.common.basevo.User;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.web.mem.member.util.FormDataUtil;
import com.sun.star.io.IOException;

/**
 * FileUploadController
 * <p>Company: itic</p>
 * @author: shijun
 * @date: 2015年5月8日 下午3:41:21
 * @version: V1.0
 */
@Controller
@RequestMapping(value = "/fileUpload")
public class FileUploadController
        extends BaseController{
    @Autowired
    private FileUploadService fileUploadService;
    @Autowired
    private FilesService filesService;
    
    @RequestMapping(value = "init",method=RequestMethod.GET)
    public String initMain(){
        return "/test/fileUpload";
    }
    
	@RequestMapping(value="imageUpload")
	@ResponseBody
	public Map<String, Object> save(@RequestParam(value="imgFile")MultipartFile imgFile,HttpServletRequest request) throws IOException{
	   // String url = OSSUtill.saveImg(imgFile.getOriginalFilename(), imgFile.getInputStream(), imgFile.getSize());
		//上传图片
		String originalFilename=imgFile.getOriginalFilename();
		System.out.println("真实文件名是:"+originalFilename);
		String filePath = null;
		if (imgFile!=null&&originalFilename!=null&&originalFilename.length()>0){
			System.out.println("*********************************4******************************");
    	      InputStream inputStream = null;
    	      try {
    	    	  System.out.println("*********************************5******************************");
    	      	inputStream = imgFile.getInputStream();
    	      	filePath = FormDataUtil.inputStreamUpload("http://47.94.128.203:8080/FileServer/upload",inputStream,"admin","1","image","T_DB_KINGEDITER_TEMPLET");
		      } catch (Exception e) {
		      	// TODO: handle exception
		      }
		}
	    Map<String, Object> map = new HashMap<String,Object>();
	    map.put("error",0);
	    System.out.println("url:"+filePath);
	    map.put("url",filePath);
		return map;
	}
    
    /**
     * 文件上传 -文件信息保存到数据库
     * 
     * @param file
     * @param mTName
     * @return String
     */
    @RequestMapping(value = "/uploadWithDB")
    @ResponseBody
    public Map<String,Object> fileUploadWithDB(Files files,
            HttpServletRequest request) {
        Map<String,Object> result = new HashMap<String,Object>();
        try {
            result = fileUpload(files, request, true);
        } catch (UnsupportedEncodingException e) {
            LOGGER.info("FileUploadController|uploadFileWithDB(文件上传)出错", e);
            throw new RuntimeException(ResponseCode.SERVER_ERROR.getCode(), e);
        }
        return result;
    }
    
    /**
     * 删除服务器文件
     * @param id
     * @return
     */
    @RequestMapping(value = "/delFile")
    @ResponseBody
    public Map<String, String> delFile(String id){
        Map<String,String> dataMap = new HashMap<String,String>();
        dataMap.put(IticConst.RESULT, ResponseCode.SERVER_ERROR.getCode());
        if (StringHelper.isNotBlank(id)){
            String reslut = filesService.delFile(id);
            dataMap.put(IticConst.RESULT, reslut);
        }
        return dataMap;
    }
    
    /**
     * 文件上传 -文件只保存到服务器
     * @param file
     * @param mTName
     * @return String
     */
    @RequestMapping(value = "/uploadWithOutDB")
    @ResponseBody
    public Map<String,Object> fileUploadWithOutDB(Files files,HttpServletRequest request) {
        Map<String,Object> result = new HashMap<String,Object>();
        String tableName = files.getTableName();
        try {
            User user = findUserSession(request);
            if(null!=user){
                if(StringHelper.isBlank(tableName)){//上传文件所在的父文件夹不存在
                    tableName = user.getOrganizationCode();
                }
                result = fileUpload(files, request, false);
            }else{
                result.put(IticConst.RESULT, ResponseCode.NOT_LOGIN.getCode());//文件验证不通过
            }
        } catch (UnsupportedEncodingException e) {
            LOGGER.info("FileUploadController|uploadFileWithDB(文件上传)出错", e);
            throw new RuntimeException(ResponseCode.SERVER_ERROR.getCode(), e);
        }
        return result;
    }
    
    /**
     * 校验并上传附件
     * @param mTName  父文件夹
     * @param request 
     * @param dbFlag 是否存数据库；true:存库；false:不存库
     * @return
     * @throws UnsupportedEncodingException
     */
    @SuppressWarnings("unchecked")
    private Map<String,Object> fileUpload(Files files, HttpServletRequest request,boolean dbFlag) 
            throws UnsupportedEncodingException {
        Map<String, Object> result = new HashMap<String,Object>();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) { // 判断request是否有文件上传
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            multiRequest.setCharacterEncoding(request.getCharacterEncoding());// 获取编码格式
            
            //分离出正常文件和过大文件
            Map<String, Object> fileDataMap = fileUploadValidators(multiRequest);
            List<MultipartFile> availableFile = (List<MultipartFile>) fileDataMap.get("availableFile");// 验证通过文件
            List<Map<String, Object>> unavailableFile = (List<Map<String, Object>>) fileDataMap.get("unavailableFile");// 验证不通过文件
            
            //有不符合的文件就不上传返回
            if (unavailableFile != null && !unavailableFile.isEmpty()) {// 验证不通过
                result.put(IticConst.RESULT, ResponseCode.PARAM_INVALID.getCode());//文件验证不通过
            }else{
                result = fileUploadService.uploadFile(availableFile, files, dbFlag);
            }
        } else {
            result.put(IticConst.RESULT, "isNotMultipart");// 非文件上传
        }
        return result;
    }
    
    /**
     * 多文件上传校验
     * @param multiRequest
     * @return Map<String,Object> 可用文件和不可用文件
     */
    private  Map<String,Object> fileUploadValidators(MultipartHttpServletRequest multiRequest){
        Map<String,Object> fileDataMap = new HashMap<String,Object>();
        List<MultipartFile> availableFile = new ArrayList<MultipartFile>();//可用文件列表
        List<Map<String,Object>> unavailableFile = new ArrayList<Map<String,Object>>();//不可用文件信息列表
        Iterator<String> iterator = multiRequest.getFileNames();//实现多文件上传，需要使<input type="file" name="file1">中的name值不同，如name="file1"，name="file2"
          while(iterator.hasNext()){
            MultipartFile file = multiRequest.getFile(iterator.next());
            if(null!=file){
                if(file.isEmpty()||StringHelper.isBlank(file.getOriginalFilename())){//过滤没有文件的input标签
                    continue;
                }
                String validatorInfo = new FileValidatorHelper().fileValidator(file);//获取验证信息
                if(StringHelper.isNotBlank(validatorInfo)&&!"true".equals(validatorInfo)){//验证不通过
                    Map<String,Object> unavailableMap = new HashMap<String, Object>();
                    unavailableMap.put("errorInfo", validatorInfo);
                    unavailableMap.put("file", file);
                    unavailableFile.add(unavailableMap);//添加文件到不可用文件list
                }else{
                    availableFile.add(file);//添加文件到可用文件list
                }
            }
        }
        fileDataMap.put("availableFile", availableFile);//验证通过文件
        fileDataMap.put("unavailableFile", unavailableFile);//验证不通过文件
        return fileDataMap;
    }
    
    /**
     * 根据文件Id、字段名称组装文件信息
     * @return
     */
    @RequestMapping(value = "/getFileInfo")
    @ResponseBody
    public Map<String, Object> getFileInfo(HttpServletRequest request,String fileIds,String field, Model model) {
        Map<String,Object> fileData = new HashMap<String,Object>();
        Map<String,Object> fileItem = new HashMap<String,Object>();
        if (StringHelper.isNotBlank(fileIds)){
            List<Files> files = filesService.getFiles(fileIds);
            List<Map<String,Object>> fileList = new ArrayList<Map<String,Object>>();
            for (Files files2 : files) {
                Map<String,Object> file = new HashMap<String,Object>();
                file.put("id", files2.getId());
                file.put("name", files2.getFileName());
                file.put("size", FileHelper.getFileSize(FileHelper.getRootDir() + files2.getFilePath()));
                file.put("path", files2.getFilePath());
                fileList.add(file);
            }
            fileItem.put(field, fileList);
            fileData.put(IticConst.DATA, fileItem);
            fileData.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        }
      return fileData;
    }
}
